
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>使用基于类的视图处理表单 &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="在基于类的视图中使用混入" href="mixins.html" />
    <link rel="prev" title="内置的基于类的通用视图" href="generic-display.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="generic-display.html" title="内置的基于类的通用视图">previous</a>
     |
    <a href="../index.html" title="使用 Django" accesskey="U">up</a>
   |
    <a href="mixins.html" title="在基于类的视图中使用混入">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-class-based-views-generic-editing">
            
  <div class="section" id="s-form-handling-with-class-based-views">
<span id="form-handling-with-class-based-views"></span><h1>使用基于类的视图处理表单<a class="headerlink" href="#form-handling-with-class-based-views" title="永久链接至标题">¶</a></h1>
<p>表单处理通常有3个途径：</p>
<ul class="simple">
<li>初始 GET （空白或预填充表单）</li>
<li>带有合法数据的POST（通常是带有错误的重新显示的表单）</li>
<li>带有合法数据的POST（处理数据和通常重定向）</li>
</ul>
<p>自己实现这个会导致很多重复的样板代码（查看 <a class="reference internal" href="../forms/index.html#using-a-form-in-a-view"><span class="std std-ref">Using a form in a view</span></a> ）。为了避免这个问题，Django 提供了一组通用基于类的视图来处理表单。</p>
<div class="section" id="s-basic-forms">
<span id="basic-forms"></span><h2>基础表单<a class="headerlink" href="#basic-forms" title="永久链接至标题">¶</a></h2>
<p>提供联系表单：</p>
<div class="literal-block-wrapper docutils container" id="id2">
<div class="code-block-caption"><span class="caption-text">forms.py</span><a class="headerlink" href="#id2" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">forms</span>

<span class="k">class</span> <span class="nc">ContactForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">Form</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">()</span>
    <span class="n">message</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">widget</span><span class="o">=</span><span class="n">forms</span><span class="o">.</span><span class="n">Textarea</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">send_email</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># send email using the self.cleaned_data dictionary</span>
        <span class="k">pass</span>
</pre></div>
</div>
</div>
<p>可以使用 <code class="docutils literal notranslate"><span class="pre">FormView</span></code> 构建视图：</p>
<div class="literal-block-wrapper docutils container" id="id3">
<div class="code-block-caption"><span class="caption-text">views.py</span><a class="headerlink" href="#id3" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">myapp.forms</span> <span class="kn">import</span> <span class="n">ContactForm</span>
<span class="kn">from</span> <span class="nn">django.views.generic.edit</span> <span class="kn">import</span> <span class="n">FormView</span>

<span class="k">class</span> <span class="nc">ContactFormView</span><span class="p">(</span><span class="n">FormView</span><span class="p">):</span>
    <span class="n">template_name</span> <span class="o">=</span> <span class="s1">&#39;contact.html&#39;</span>
    <span class="n">form_class</span> <span class="o">=</span> <span class="n">ContactForm</span>
    <span class="n">success_url</span> <span class="o">=</span> <span class="s1">&#39;/thanks/&#39;</span>

    <span class="k">def</span> <span class="nf">form_valid</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">form</span><span class="p">):</span>
        <span class="c1"># This method is called when valid form data has been POSTed.</span>
        <span class="c1"># It should return an HttpResponse.</span>
        <span class="n">form</span><span class="o">.</span><span class="n">send_email</span><span class="p">()</span>
        <span class="k">return</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">form_valid</span><span class="p">(</span><span class="n">form</span><span class="p">)</span>
</pre></div>
</div>
</div>
<p>注意：</p>
<ul class="simple">
<li>FormView 继承了 <a class="reference internal" href="../../ref/class-based-views/mixins-simple.html#django.views.generic.base.TemplateResponseMixin" title="django.views.generic.base.TemplateResponseMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemplateResponseMixin</span></code></a> ，因此可以在这里使用 <a class="reference internal" href="../../ref/class-based-views/mixins-simple.html#django.views.generic.base.TemplateResponseMixin.template_name" title="django.views.generic.base.TemplateResponseMixin.template_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">template_name</span></code></a> 。</li>
<li>默认实现了 <a class="reference internal" href="../../ref/class-based-views/mixins-editing.html#django.views.generic.edit.FormMixin.form_valid" title="django.views.generic.edit.FormMixin.form_valid"><code class="xref py py-meth docutils literal notranslate"><span class="pre">form_valid()</span></code></a>&nbsp; 简单重定向至 <a class="reference internal" href="../../ref/class-based-views/mixins-editing.html#django.views.generic.edit.FormMixin.success_url" title="django.views.generic.edit.FormMixin.success_url"><code class="xref py py-attr docutils literal notranslate"><span class="pre">success_url</span></code></a> 。</li>
</ul>
</div>
<div class="section" id="s-model-forms">
<span id="model-forms"></span><h2>模型表单<a class="headerlink" href="#model-forms" title="永久链接至标题">¶</a></h2>
<p>通用视图在模型一起工作时真的很赞。这些通用视图将自动创建 <a class="reference internal" href="../forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelForm</span></code></a> ，只要他们能找出要使用的模型类：</p>
<ul class="simple">
<li>如果已经给出了 <a class="reference internal" href="../../ref/class-based-views/mixins-editing.html#django.views.generic.edit.ModelFormMixin.model" title="django.views.generic.edit.ModelFormMixin.model"><code class="xref py py-attr docutils literal notranslate"><span class="pre">model</span></code></a>&nbsp;属性，则使用这个模型类。</li>
<li>如果 <a class="reference internal" href="../../ref/class-based-views/mixins-single-object.html#django.views.generic.detail.SingleObjectMixin.get_object" title="django.views.generic.detail.SingleObjectMixin.get_object"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_object()</span></code></a>&nbsp;返回一个对象，则使用这个对象的类。</li>
<li>如果已经给出了 <a class="reference internal" href="../../ref/class-based-views/mixins-single-object.html#django.views.generic.detail.SingleObjectMixin.queryset" title="django.views.generic.detail.SingleObjectMixin.queryset"><code class="xref py py-attr docutils literal notranslate"><span class="pre">queryset</span></code></a>&nbsp; ，则使用这个查询集的模型。</li>
</ul>
<p>模型表单视图提供一个 <a class="reference internal" href="../../ref/class-based-views/mixins-editing.html#django.views.generic.edit.ModelFormMixin.form_valid" title="django.views.generic.edit.ModelFormMixin.form_valid"><code class="xref py py-meth docutils literal notranslate"><span class="pre">form_valid()</span></code></a>&nbsp;实现，来自动保存模型。如果你有特别的需求，你可以覆盖它。下面是例子。</p>
<p>你甚至不需要为 <a class="reference internal" href="../../ref/class-based-views/generic-editing.html#django.views.generic.edit.CreateView" title="django.views.generic.edit.CreateView"><code class="xref py py-class docutils literal notranslate"><span class="pre">CreateView</span></code></a> 或 <a class="reference internal" href="../../ref/class-based-views/generic-editing.html#django.views.generic.edit.UpdateView" title="django.views.generic.edit.UpdateView"><code class="xref py py-class docutils literal notranslate"><span class="pre">UpdateView</span></code></a> 提供 <code class="docutils literal notranslate"><span class="pre">success_url</span></code>&nbsp;。如果可用，它们将在模型对象上使用 <a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.get_absolute_url" title="django.db.models.Model.get_absolute_url"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_absolute_url()</span></code></a> 。</p>
<p>如果你想使用一个自定义的  <a class="reference internal" href="../forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelForm</span></code></a> （比如添加额外的验证），用来在视图上设置 <a class="reference internal" href="../../ref/class-based-views/mixins-editing.html#django.views.generic.edit.FormMixin.form_class" title="django.views.generic.edit.FormMixin.form_class"><code class="xref py py-attr docutils literal notranslate"><span class="pre">form_class</span></code></a> 。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">当指定一个自定义表单类时，必须也要指定模型，即使 <a class="reference internal" href="../../ref/class-based-views/mixins-editing.html#django.views.generic.edit.FormMixin.form_class" title="django.views.generic.edit.FormMixin.form_class"><code class="xref py py-attr docutils literal notranslate"><span class="pre">form_class</span></code></a> 可能是一个 <a class="reference internal" href="../forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelForm</span></code></a> 。</p>
</div>
<p>首先我们需要添加 <a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.get_absolute_url" title="django.db.models.Model.get_absolute_url"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_absolute_url()</span></code></a> 到 <code class="docutils literal notranslate"><span class="pre">Author</span></code> 类：</p>
<div class="literal-block-wrapper docutils container" id="id4">
<div class="code-block-caption"><span class="caption-text">models.py</span><a class="headerlink" href="#id4" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">reverse</span>

<span class="k">class</span> <span class="nc">Author</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">get_absolute_url</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">reverse</span><span class="p">(</span><span class="s1">&#39;author-detail&#39;</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;pk&#39;</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">pk</span><span class="p">})</span>
</pre></div>
</div>
</div>
<p>然后可以使用 <a class="reference internal" href="../../ref/class-based-views/flattened-index.html#CreateView" title="CreateView"><code class="xref py py-class docutils literal notranslate"><span class="pre">CreateView</span></code></a>&nbsp;并友好的执行实际工作。注意这里我们如何配置通用基于类的视图。我们不用自己编写任何逻辑：</p>
<div class="literal-block-wrapper docutils container" id="id5">
<div class="code-block-caption"><span class="caption-text">views.py</span><a class="headerlink" href="#id5" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">reverse_lazy</span>
<span class="kn">from</span> <span class="nn">django.views.generic.edit</span> <span class="kn">import</span> <span class="n">CreateView</span><span class="p">,</span> <span class="n">DeleteView</span><span class="p">,</span> <span class="n">UpdateView</span>
<span class="kn">from</span> <span class="nn">myapp.models</span> <span class="kn">import</span> <span class="n">Author</span>

<span class="k">class</span> <span class="nc">AuthorCreateView</span><span class="p">(</span><span class="n">CreateView</span><span class="p">):</span>
    <span class="n">model</span> <span class="o">=</span> <span class="n">Author</span>
    <span class="n">fields</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;name&#39;</span><span class="p">]</span>

<span class="k">class</span> <span class="nc">AuthorUpdateView</span><span class="p">(</span><span class="n">UpdateView</span><span class="p">):</span>
    <span class="n">model</span> <span class="o">=</span> <span class="n">Author</span>
    <span class="n">fields</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;name&#39;</span><span class="p">]</span>

<span class="k">class</span> <span class="nc">AuthorDeleteView</span><span class="p">(</span><span class="n">DeleteView</span><span class="p">):</span>
    <span class="n">model</span> <span class="o">=</span> <span class="n">Author</span>
    <span class="n">success_url</span> <span class="o">=</span> <span class="n">reverse_lazy</span><span class="p">(</span><span class="s1">&#39;author-list&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">我们必须在这里使用 <a class="reference internal" href="../../ref/urlresolvers.html#django.urls.reverse_lazy" title="django.urls.reverse_lazy"><code class="xref py py-func docutils literal notranslate"><span class="pre">reverse_lazy()</span></code></a> 来代替 <code class="docutils literal notranslate"><span class="pre">reverse()</span></code> ，因为在文件导入时不加载  urls 。</p>
</div>
<p><code class="docutils literal notranslate"><span class="pre">fields</span></code> 属性的工作方式同 <a class="reference internal" href="../forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelForm</span></code></a> 中内部 <code class="docutils literal notranslate"><span class="pre">Meta</span></code> 类的 <code class="docutils literal notranslate"><span class="pre">fields</span></code> 属性一样。除非你使用其他方式定义表单类，该属性是必需的，如果属性不存在，视图将引发 <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.ImproperlyConfigured" title="django.core.exceptions.ImproperlyConfigured"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImproperlyConfigured</span></code></a> 异常。</p>
<p>如果同时指定了 <a class="reference internal" href="../../ref/class-based-views/mixins-editing.html#django.views.generic.edit.ModelFormMixin.fields" title="django.views.generic.edit.ModelFormMixin.fields"><code class="xref py py-attr docutils literal notranslate"><span class="pre">fields</span></code></a> 和 <a class="reference internal" href="../../ref/class-based-views/mixins-editing.html#django.views.generic.edit.FormMixin.form_class" title="django.views.generic.edit.FormMixin.form_class"><code class="xref py py-attr docutils literal notranslate"><span class="pre">form_class</span></code></a>&nbsp;属性，将会引发 <a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.ImproperlyConfigured" title="django.core.exceptions.ImproperlyConfigured"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImproperlyConfigured</span></code></a> 异常。</p>
<p>最后将这些新视图挂钩到URLconf中：</p>
<div class="literal-block-wrapper docutils container" id="id6">
<div class="code-block-caption"><span class="caption-text">urls.py</span><a class="headerlink" href="#id6" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">path</span>
<span class="kn">from</span> <span class="nn">myapp.views</span> <span class="kn">import</span> <span class="n">AuthorCreateView</span><span class="p">,</span> <span class="n">AuthorDeleteView</span><span class="p">,</span> <span class="n">AuthorUpdateView</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="c1"># ...</span>
    <span class="n">path</span><span class="p">(</span><span class="s1">&#39;author/add/&#39;</span><span class="p">,</span> <span class="n">AuthorCreateView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;author-add&#39;</span><span class="p">),</span>
    <span class="n">path</span><span class="p">(</span><span class="s1">&#39;author/&lt;int:pk&gt;/&#39;</span><span class="p">,</span> <span class="n">AuthorUpdateView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;author-update&#39;</span><span class="p">),</span>
    <span class="n">path</span><span class="p">(</span><span class="s1">&#39;author/&lt;int:pk&gt;/delete/&#39;</span><span class="p">,</span> <span class="n">AuthorDeleteView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;author-delete&#39;</span><span class="p">),</span>
<span class="p">]</span>
</pre></div>
</div>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p>这些视图继承 <a class="reference internal" href="../../ref/class-based-views/mixins-single-object.html#django.views.generic.detail.SingleObjectTemplateResponseMixin" title="django.views.generic.detail.SingleObjectTemplateResponseMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">SingleObjectTemplateResponseMixin</span></code></a> ，它使用 <a class="reference internal" href="../../ref/class-based-views/mixins-single-object.html#django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix" title="django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix"><code class="xref py py-attr docutils literal notranslate"><span class="pre">template_name_suffix</span></code></a> 来构建基于模型的 <a class="reference internal" href="../../ref/class-based-views/mixins-simple.html#django.views.generic.base.TemplateResponseMixin.template_name" title="django.views.generic.base.TemplateResponseMixin.template_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">template_name</span></code></a> 。</p>
<p>在这个例子里：</p>
<ul class="simple">
<li><a class="reference internal" href="../../ref/class-based-views/flattened-index.html#CreateView" title="CreateView"><code class="xref py py-class docutils literal notranslate"><span class="pre">CreateView</span></code></a> 和 <a class="reference internal" href="../../ref/class-based-views/flattened-index.html#UpdateView" title="UpdateView"><code class="xref py py-class docutils literal notranslate"><span class="pre">UpdateView</span></code></a> 使用 <code class="docutils literal notranslate"><span class="pre">myapp/author_form.html</span></code> 。</li>
<li><a class="reference internal" href="../../ref/class-based-views/flattened-index.html#DeleteView" title="DeleteView"><code class="xref py py-class docutils literal notranslate"><span class="pre">DeleteView</span></code></a> 使用 <code class="docutils literal notranslate"><span class="pre">myapp/author_confirm_delete.html</span></code> 。</li>
</ul>
<p class="last">如果你想为 <a class="reference internal" href="../../ref/class-based-views/flattened-index.html#CreateView" title="CreateView"><code class="xref py py-class docutils literal notranslate"><span class="pre">CreateView</span></code></a> 和 <a class="reference internal" href="../../ref/class-based-views/flattened-index.html#UpdateView" title="UpdateView"><code class="xref py py-class docutils literal notranslate"><span class="pre">UpdateView</span></code></a> 制作单独的模板，你可以在视图类上设置 <a class="reference internal" href="../../ref/class-based-views/mixins-simple.html#django.views.generic.base.TemplateResponseMixin.template_name" title="django.views.generic.base.TemplateResponseMixin.template_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">template_name</span></code></a> 或 <a class="reference internal" href="../../ref/class-based-views/mixins-single-object.html#django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix" title="django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix"><code class="xref py py-attr docutils literal notranslate"><span class="pre">template_name_suffix</span></code></a>&nbsp;。</p>
</div>
</div>
<div class="section" id="s-models-and-request-user">
<span id="models-and-request-user"></span><h2>模型和 <code class="docutils literal notranslate"><span class="pre">request.user</span></code><a class="headerlink" href="#models-and-request-user" title="永久链接至标题">¶</a></h2>
<p>若要跟踪使用 <a class="reference internal" href="../../ref/class-based-views/flattened-index.html#CreateView" title="CreateView"><code class="xref py py-class docutils literal notranslate"><span class="pre">CreateView</span></code></a> 创建的用户，你可以使用自定义的 <a class="reference internal" href="../forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelForm</span></code></a>&nbsp;来执行此操作。首先，在模型里添加外键关系：</p>
<div class="literal-block-wrapper docutils container" id="id7">
<div class="code-block-caption"><span class="caption-text">models.py</span><a class="headerlink" href="#id7" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.models</span> <span class="kn">import</span> <span class="n">User</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Author</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">)</span>
    <span class="n">created_by</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">User</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>

    <span class="c1"># ...</span>
</pre></div>
</div>
</div>
<p>在这个视图中，确保你没有在要编辑的字段列表中包含 <code class="docutils literal notranslate"><span class="pre">created_by</span></code> 字段 ，并且要覆盖 <a class="reference internal" href="../../ref/class-based-views/mixins-editing.html#django.views.generic.edit.ModelFormMixin.form_valid" title="django.views.generic.edit.ModelFormMixin.form_valid"><code class="xref py py-meth docutils literal notranslate"><span class="pre">form_valid()</span></code></a> 来添加用户：</p>
<div class="literal-block-wrapper docutils container" id="id8">
<div class="code-block-caption"><span class="caption-text">views.py</span><a class="headerlink" href="#id8" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.auth.mixins</span> <span class="kn">import</span> <span class="n">LoginRequiredMixin</span>
<span class="kn">from</span> <span class="nn">django.views.generic.edit</span> <span class="kn">import</span> <span class="n">CreateView</span>
<span class="kn">from</span> <span class="nn">myapp.models</span> <span class="kn">import</span> <span class="n">Author</span>

<span class="k">class</span> <span class="nc">AuthorCreateView</span><span class="p">(</span><span class="n">LoginRequiredMixin</span><span class="p">,</span> <span class="n">CreateView</span><span class="p">):</span>
    <span class="n">model</span> <span class="o">=</span> <span class="n">Author</span>
    <span class="n">fields</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;name&#39;</span><span class="p">]</span>

    <span class="k">def</span> <span class="nf">form_valid</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">form</span><span class="p">):</span>
        <span class="n">form</span><span class="o">.</span><span class="n">instance</span><span class="o">.</span><span class="n">created_by</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">user</span>
        <span class="k">return</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">form_valid</span><span class="p">(</span><span class="n">form</span><span class="p">)</span>
</pre></div>
</div>
</div>
<p><a class="reference internal" href="../auth/default.html#django.contrib.auth.mixins.LoginRequiredMixin" title="django.contrib.auth.mixins.LoginRequiredMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">LoginRequiredMixin</span></code></a> 防止那些未登录的用户访问表单。如果忽略，那么你将需要在 <a class="reference internal" href="../../ref/class-based-views/mixins-editing.html#django.views.generic.edit.ModelFormMixin.form_valid" title="django.views.generic.edit.ModelFormMixin.form_valid"><code class="xref py py-meth docutils literal notranslate"><span class="pre">form_valid()</span></code></a> 里处理未授权的用户。</p>
</div>
<div class="section" id="s-content-negotiation-example">
<span id="s-id1"></span><span id="content-negotiation-example"></span><span id="id1"></span><h2>内容协商示例<a class="headerlink" href="#content-negotiation-example" title="永久链接至标题">¶</a></h2>
<p>下面是一个展示了如何实现基于API的工作流以及普通POST表单一起使用的表单：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">JsonResponse</span>
<span class="kn">from</span> <span class="nn">django.views.generic.edit</span> <span class="kn">import</span> <span class="n">CreateView</span>
<span class="kn">from</span> <span class="nn">myapp.models</span> <span class="kn">import</span> <span class="n">Author</span>

<span class="k">class</span> <span class="nc">JsonableResponseMixin</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Mixin to add JSON support to a form.</span>
<span class="sd">    Must be used with an object-based FormView (e.g. CreateView)</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">def</span> <span class="nf">form_invalid</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">form</span><span class="p">):</span>
        <span class="n">response</span> <span class="o">=</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">form_invalid</span><span class="p">(</span><span class="n">form</span><span class="p">)</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">accepts</span><span class="p">(</span><span class="s1">&#39;text/html&#39;</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">response</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">JsonResponse</span><span class="p">(</span><span class="n">form</span><span class="o">.</span><span class="n">errors</span><span class="p">,</span> <span class="n">status</span><span class="o">=</span><span class="mi">400</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">form_valid</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">form</span><span class="p">):</span>
        <span class="c1"># We make sure to call the parent&#39;s form_valid() method because</span>
        <span class="c1"># it might do some processing (in the case of CreateView, it will</span>
        <span class="c1"># call form.save() for example).</span>
        <span class="n">response</span> <span class="o">=</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">form_valid</span><span class="p">(</span><span class="n">form</span><span class="p">)</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">accepts</span><span class="p">(</span><span class="s1">&#39;text/html&#39;</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">response</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">data</span> <span class="o">=</span> <span class="p">{</span>
                <span class="s1">&#39;pk&#39;</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">object</span><span class="o">.</span><span class="n">pk</span><span class="p">,</span>
            <span class="p">}</span>
            <span class="k">return</span> <span class="n">JsonResponse</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">AuthorCreateView</span><span class="p">(</span><span class="n">JsonableResponseMixin</span><span class="p">,</span> <span class="n">CreateView</span><span class="p">):</span>
    <span class="n">model</span> <span class="o">=</span> <span class="n">Author</span>
    <span class="n">fields</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;name&#39;</span><span class="p">]</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">使用基于类的视图处理表单</a><ul>
<li><a class="reference internal" href="#basic-forms">基础表单</a></li>
<li><a class="reference internal" href="#model-forms">模型表单</a></li>
<li><a class="reference internal" href="#models-and-request-user">模型和 <code class="docutils literal notranslate"><span class="pre">request.user</span></code></a></li>
<li><a class="reference internal" href="#content-negotiation-example">内容协商示例</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="generic-display.html"
                        title="上一章">内置的基于类的通用视图</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="mixins.html"
                        title="下一章">在基于类的视图中使用混入</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/topics/class-based-views/generic-editing.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="generic-display.html" title="内置的基于类的通用视图">previous</a>
     |
    <a href="../index.html" title="使用 Django" accesskey="U">up</a>
   |
    <a href="mixins.html" title="在基于类的视图中使用混入">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>